<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\member\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\member\model\goods as goodsModel;
use function GuzzleHttp\Psr7\uri_for;
use think\db;

/**
 * 系统模块控制器
 * @package app\admin\controller
 */
class Goods extends Admin
{
    /**
     * 系统设置
     * @param string $group 分组
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function index()
    {
        // 保存数据
        // 查询
        $map = $this->getMap();
        // 排序   // 排序
        $order = $this->getOrder('a.id desc');
        $data_list = DB::name('goods')->alias('a')->join('category b','a.category_id=b.id','left')->field('a.id,a.goods_name,a.goods_image,a.goods_images,a.goods_label,a.goods_type,a.addtime,b.category_name,a.category_id')->where(['a.del'=>0])->order($order)->where($map)
            ->paginate(10); //查询会员表所有信息
        $specialty = [
            'title' => '商品属性',
            'icon'  => 'fa fa-fw fa-tags',
            'href'  => url('specialty', ['id' => '__id__']),
        ];
//        $data_list = goodsModel::where($map)->order('id desc')->paginate();
        $goods_type = [1=>'上架',2=>'下架'];
        // 分页数据
        $page = $data_list->render();
        $category_id=Db::name('category')->where(['del'=>0])->column('id,category_name');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('商品列表') // 设置页面标题
            ->setSearchArea([
                ['text:2', 'a.goods_name', '商品名称', 'like'],
                ['select:3', 'a.goods_type', '类型','','',$goods_type],
                ['select:3', 'a.category_id', '分类','','',$category_id],
            ])
//            ->setSearch(['title' => '名称']) // 设置搜索框

            ->addColumns([ // 批量添加数据列
                ['id', '编号'],
                ['category_name', '分类名称'],
                ['goods_name', '商品名称'],
                ['goods_image', '商品封面图','picture'],
                ['goods_images', '商品轮播图','pictures'],
                ['goods_label', '商品标签'],
                ['goods_type', '类型', 'status', '',$goods_type],
                ['addtime', '执行时间', 'time', '', 'Y-m-d H:i:s'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add') // 批量添加顶部按钮
//            ->addRightButton('custom', $btn_access) // 添加授权按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->addRightButton('specialty',$specialty)
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    public function add()
    {
        // 保存数据
        if ($_POST) {
            // 验证
            $data = $_POST;
//            dump($data);die;
            // 验证失败 输出错误信息
            if(empty($data['category_id'])){
                $this->error('请选择分类');
            }
            if (empty($data['goods_name'])){
                $this->error('请填写商品名称');
            }
            if (empty($data['goods_images'])){
                $this->error('请上传商品轮播图');
            }
            if (empty($data['goods_image'])){
                $this->error('请上传商品封面图');
            }
            if (empty($data['goods_label'])){
                $this->error('请填写标签');
            }
            if (empty($data['goods_details'])){
                $this->error('请填写详情');
            }
//                if (empty($data['rebate'])){
//                    $this->error('请填写返利金额');
//                }
            if ($data['discounting_price']<0){
                $this->error('请填写正确的抵现金额');
            }
            $data['addtime']=time();
            $result = Db::name('goods')->insert($data);
            if ($result) {
                $this->success('添加成功', 'index');
            } else {
                $this->error('添加失败');
            }
        }
        $goods_type = [1=>'上架',2=>'下架'];
        // 使用ZBuilder快速创建表单
        $category=  DB::name('category')->where(['del'=>0])->column('id,category_name');
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
//            ->hideCheckbox()//设置 是否隐藏多选框
            ->addSelect('category_id', '请选择分类', '',$category)
            ->addFormItems([ // 批量添加表单项
                ['text','goods_name','商品名称'],
                ['images','goods_images','商品轮播图'],
                ['image','goods_image','商品封面图'],
                ['tags','goods_label','标签'],
                ['text','discounting_price','商品积分抵扣金额',0],
                ['radio', 'goods_type', '类型：','',$goods_type,'1'],
                ['ueditor', 'goods_details', '详情',],
            ])
            ->fetch();
    }

    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $_POST;
            if(empty($data['category_id'])){
                $this->error('请选择分类');
            }
            if (empty($data['goods_name'])){
                $this->error('请填写商品名称');
            }
            if (empty($data['goods_images'])){
                $this->error('请上传商品轮播图');
            }
            if (empty($data['goods_image'])){
                $this->error('请上传商品封面图');
            }
            if (empty($data['goods_label'])){
                $this->error('请填写标签');
            }
            if (empty($data['goods_details'])){
                $this->error('请填写详情');
            }
//            $admin_goods=db('admin_goods')->where(['goods_type'=>2,'del'=>0])->count();
            $data['updatatime']=time();
            $result = db('goods')->where('id',$id)->update($data);;
            if ($result){
                $this->success('修改成功', 'index');
            }else {
                $this->error('修改失败');
            }
        }
        // 获取数据
        $info = db('goods')->where('id='.$id)->find();
        $goods_type = [1=>'上架',2=>'下架'];
        // 使用ZBuilder快速创建表单
//        dump($pid);die;
        $category=  DB::name('category')->where(['del'=>0])->column('id,category_name');
        return ZBuilder::make('form')
//            ->setPageTitle('编辑') // 设置页面标题
            ->addSelect('category_id', '请选择分类', '',$category)
            ->addFormItems([ // 批量添加表单项
                ['text','goods_name','商品名称'],
                ['images','goods_images','商品轮播图'],
                ['image','goods_image','商品封面图'],
                ['tags','goods_label','标签'],
                ['text','discounting_price','商品积分抵扣金额',0],
                ['radio', 'goods_type', '类型：','',$goods_type,'1'],
                ['ueditor', 'goods_details', '详情',],
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    public function delete($ids = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');

        db('goods')->where('id',$ids)->setField(array('del'=>1));
        $this->success('删除成功！');
    }

    public function specialty($id=null){
        $map = $this->getMap();
        $adds = [
            'title' => '新增',
            'icon'  => 'fa fa-fw fa-plus',
            'href'  => url('adds', ['id' => $id]),
        ];
        $edits = [
            'title' => '专业编辑',
            'icon'  => 'fa fa-fw fa-pencil',
            'href'  => url('edits', ['id' => '__id__']),
        ];
        $deletes = [
            'title' => '删除专业',
            'icon'  => 'fa fa-fw fa-remove',
            'href'  => url('deletes', ['id' => '__id__']),
        ];
        $datalist=db('nature')->where(['good_id'=>$id,'del'=>0])->field('id,nature_name,nature_price,addtime')->where($map)
            ->order('id desc')
            ->paginate(10)
            ->each(function($item, $key){
                return $item;
            });
        return ZBuilder::make('table')
            ->setSearchArea([
                ['text:2', 'nature_name', '属性名称','like'],
            ])
            ->hideCheckbox()
            ->hideColumn('id')
            ->addColumns([
                ['__INDEX__', 'ID'],
                ['nature_name', '属性名称'],
                ['nature_price', '金额'],
                ['addtime', '时间','datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->setRowlist($datalist)
            ->addTopButton('adds', $adds) // 添加授权按钮
            ->addRightButton('edits',$edits)
            ->addRightButton('deletes',$deletes)
//            ->addRightButtons('edit,delete')
            ->fetch();
    }
    public function adds($id=null){
        if ($this->request->isPost()) {
            $data = input('post.');
            $num='/^(0|[0-9]\d{0,7})(\.\d{1,2})?$/';
            if ( $data['nature_price']<=0){
                $this->error('请检查金额');
            }
            if(!preg_match_all($num, $data['nature_price']) ){
                $this->error('请检查金额');
            }
            if (empty($data['nature_name'])){
                $this->error('请填写属性名称');
            }
            $data['good_id']=$id;

            $data['addtime']=time();
            $result = db('nature')->insert($data);
            if ($result) {
//                'general?id='.$id
                $this->success('添加成功', 'specialty?id='.$id);
            } else {
                $this->error('添加失败');
            }
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['text','nature_name', '属性名称'],
                ['text','nature_price', '价格'],
            ])

            ->fetch();
    }

    public function edits($id=null){
        if ($this->request->isPost()) {
            $data = input('post.');

            $num='/^(0|[0-9]\d{0,7})(\.\d{1,2})?$/';
            if ( $data['nature_price']<=0){
                $this->error('请检查金额');
            }
            if(!preg_match_all($num, $data['nature_price']) ){
                $this->error('请检查金额');
            }
            if (empty($data['nature_name'])){
                $this->error('请填写属性名称');
            }
            $schools=db('nature')->where(['id'=>$id])->value('good_id');
            $data['updatatime']=time();
            $result = db('nature')->where(['id'=>$id])->update($data);
            if ($result) {

                $this->success('修改成功', 'specialty?id='.$schools);
            } else {
                $this->error('修改失败');
            }
        }
        $datalist=db('nature')->where(['id'=>$id])->find();
        return ZBuilder::make('form')
            ->addFormItems([
                ['text','nature_name', '属性名称'],
                ['text','nature_price', '价格'],
            ])

            ->setFormData($datalist)
            ->fetch();
    }

    public function deletes($id =null)
    {
        $school=db('nature')->where(['id'=>$id])->value('good_id');

        $rs = Db::name('nature')->where('id',$id)->setField('del',1);
        if ($rs){
            $this->success('删除成功','specialty?id='.$school);
        }
        $this->error('删除失败');
    }
}